package top.healthylife.gateway.mgr.controller;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import top.healthylife.basics.utils.exception.BusinessException;
import top.healthylife.basics.utils.utils.R;
import top.healthylife.gateway.mgr.component.ApiComponent;
import top.healthylife.gateway.mgr.component.GatewaySaveLogComponent;
import top.healthylife.gateway.mgr.model.Account;
import top.healthylife.gateway.mgr.service.GatewayAccountService;
import top.healthylife.gateway.mgr.service.GatewayLogService;
import top.heathylife.gateway.common.po.GatewayAccountPo;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author maoxiaomeng
 */
@Api(tags = "数据网关-账号接口")
@Slf4j
@RestController
@RequestMapping("/gateway/account")
@AllArgsConstructor
public class AccountController {
    ApiComponent apiComponent;
    RestTemplate restTemplate;
    GatewayAccountService gatewayAccountService;
    GatewaySaveLogComponent gatewaySaveLogComponent;
    GatewayLogService gatewayLogService;


    @ApiOperation("账号信息-列表")
    @GetMapping("/list")
    public R<List<GatewayAccountPo>> accountList(@RequestParam(required = false) String shortName,
                                                 @RequestParam(required = false) String secretName,
                                                 @RequestParam(required = false) String env) {
        return R.ok(gatewayAccountService.listQuery(shortName, secretName, env));
    }


    @ApiOperation("账号信息-分页")
    @GetMapping("/page")
    public R<Page<GatewayAccountPo>> accountPage(@RequestParam(required = false) String shortName,
                                                 @RequestParam(required = false) String secretName,
                                                 @RequestParam(required = false) String env,
                                                 @RequestParam(required = false, defaultValue = "1") long current,
                                                 @RequestParam(required = false, defaultValue = "7") long size) {
        Page<GatewayAccountPo> page = new Page<>(current, size);
        return R.ok(gatewayAccountService.pageQuery(shortName, secretName, env, page));
    }


    @ApiOperation("账号信息-详情")
    @GetMapping("/detail/{accountId}")
    public R<GatewayAccountPo> accountPage(@PathVariable String accountId) {
        return R.ok(gatewayAccountService.getById(accountId));
    }


    @ApiOperation("账号信息-配置")
    @PostMapping("/config")
    public R<Boolean> accountConfig(@Valid @RequestBody Account.Config config) {
        GatewayAccountPo byId = gatewayAccountService.getById(config.getAccountId());
        Optional.ofNullable(byId).orElseThrow(() -> new BusinessException("账号不存在"));
        byId.setSecretJson(JSONUtil.toJsonStr(config.getSecretJson()));
        byId.setApiPriceJson(JSONUtil.toJsonStr(config.getApiPriceConfig()));
        return R.ok(gatewayAccountService.updateById(byId));
    }


    @ApiOperation("账号信息-编辑")
    @PostMapping("/account/modify")
    public R<Boolean> accountModify(@RequestBody GatewayAccountPo accountPo) {
        GatewayAccountPo byId = gatewayAccountService.getById(accountPo.getId());
        Optional.ofNullable(byId).orElseThrow(() -> new BusinessException("账号不存在"));
        byId.setSecret(accountPo.getSecret());
        byId.setUpdateTime(LocalDateTime.now());
        byId.setShortName(accountPo.getShortName());
        return R.ok(gatewayAccountService.updateById(byId));
    }


    @ApiOperation("账号信息-删除")
    @GetMapping("/delete/{accountId}")
    public R<Boolean> accountDelete(@PathVariable String accountId) {
        GatewayAccountPo byId = gatewayAccountService.getById(accountId);
        Optional.ofNullable(byId).orElseThrow(() -> new BusinessException("账号不存在"));
        return R.ok(gatewayAccountService.removeById(byId));
    }


    @ApiOperation("账号信息-保存")
    @GetMapping("/add")
    public R<Boolean> accountAdd(String secretName, String shortName) {
        GatewayAccountPo gatewayAccountPo = new GatewayAccountPo();
        gatewayAccountPo.setSecret(IdUtil.fastSimpleUUID());
        gatewayAccountPo.setCreateTime(LocalDateTime.now());
        gatewayAccountPo.setShortName(shortName)
                .setSecretName(secretName)
                .setStatus(Boolean.FALSE);
        return R.ok(gatewayAccountService.save(gatewayAccountPo));
    }


    @ApiOperation("账号-接口配置")
    @GetMapping("/query/config")
    public R<Page<GatewayAccountPo>> accountConfig(@RequestParam(required = false) String shortName,
                                                   @RequestParam(required = false) String secretName,
                                                   @RequestParam(required = false) String env,
                                                   @RequestParam(required = false, defaultValue = "1") long current,
                                                   @RequestParam(required = false, defaultValue = "7") long size) {
        Page<GatewayAccountPo> page = new Page<>(current, size);
        return R.ok(gatewayAccountService.pageQuery(shortName, secretName, env, page));
    }


    @ApiOperation("校验账号是否可用")
    @PostMapping("/check/enable/{shortName}/{secret}")
    public R<Boolean> checkEnable(@PathVariable String shortName, @PathVariable String secret,
                                  @RequestBody Map<String, ?> jsonMap) {
        Dict dict = apiComponent.checkSecretEnable(JSONObject.toJSONString(jsonMap), secret, shortName);
        Boolean enable = (Boolean) dict.get("enable");
        String msg = dict.get("msg").toString();
        return enable ? R.ok(true, "账号可用") : R.failed(false, msg);
    }


}
